<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { login, getCurrentUser } from '../api/auth'

// 路由
const router = useRouter()

// 表单数据
const loginForm = reactive({
  username: '',
  password: ''
})

// 记住我选项
const rememberMe = ref(false)

// 登录状态
const loading = ref(false)
const errorMessage = ref('')
const showPassword = ref(false)

// 装饰背景动画
const particles = ref<Array<{x: number, y: number, size: number, speed: number, color: string}>>([])

// 登录方法
const handleLogin = async () => {
  // 表单验证
  if (!loginForm.username.trim()) {
    errorMessage.value = '请输入用户名'
    return
  }
  
  if (!loginForm.password.trim()) {
    errorMessage.value = '请输入密码'
    return
  }
  
  errorMessage.value = ''
  loading.value = true
  
  try {
    // 调用登录API
    const result = await login(loginForm.username, loginForm.password)
    
    if (result.code === 200 && result.data) {
      // 登录成功，保存token到localStorage
      localStorage.setItem('token', result.data.token)
      localStorage.setItem('user', JSON.stringify(result.data.user))
      
      // 如果选择了记住我，保存用户名到localStorage
      if (rememberMe.value) {
        localStorage.setItem('rememberedUsername', loginForm.username)
      } else {
        localStorage.removeItem('rememberedUsername')
      }
      
      // 显示成功消息
      ElMessage.success('登录成功')
      
      // 尝试获取最新的用户信息
      try {
        const userResult = await getCurrentUser()
        if (userResult.code === 200 && userResult.data) {
          localStorage.setItem('user', JSON.stringify(userResult.data))
        }
      } catch (err) {
        console.error('获取用户信息失败，将使用登录返回的用户信息', err)
      }
      
      // 获取重定向地址（如果有）
      const redirectPath = router.currentRoute.value.query.redirect as string
      
      // 确保重定向路径有效，否则跳转到主页
      if (redirectPath && typeof redirectPath === 'string' && redirectPath.startsWith('/')) {
        router.push(redirectPath)
      } else {
        router.push('/')
      }
    } else if (result.code === 401) {
      errorMessage.value = '用户名或密码错误'
    } else if (result.code === 500) {
      errorMessage.value = '服务器错误，请稍后再试'
    } else {
      errorMessage.value = result.msg || '登录失败，请重试'
    }
  } catch (error) {
    console.error('登录请求失败:', error)
    errorMessage.value = '网络错误，请检查您的网络连接'
  } finally {
    loading.value = false
  }
}

// 切换到注册页面
const goToRegister = () => {
  router.push('/register')
}

// 切换到主页
const goToHome = () => {
  router.push('/')
}

// 切换密码可见性
const togglePasswordVisibility = () => {
  showPassword.value = !showPassword.value
}

// 创建粒子效果
const initParticles = () => {
  const colors = ['#6366f1', '#8b5cf6', '#d946ef', '#ec4899', '#f43f5e']
  const particleCount = 30
  
  for (let i = 0; i < particleCount; i++) {
    particles.value.push({
      x: Math.random() * window.innerWidth,
      y: Math.random() * window.innerHeight,
      size: Math.random() * 6 + 2,
      speed: Math.random() * 0.4 + 0.1,
      color: colors[Math.floor(Math.random() * colors.length)]
    })
  }
  
  animateParticles()
}

// 动画粒子
const animateParticles = () => {
  particles.value = particles.value.map(p => {
    p.y -= p.speed
    
    // 重置回底部
    if (p.y < -10) {
      p.y = window.innerHeight + 10
      p.x = Math.random() * window.innerWidth
    }
    
    return p
  })
  
  requestAnimationFrame(animateParticles)
}

// 组件挂载时初始化粒子
onMounted(() => {
  initParticles()
  
  // 检查是否有保存的用户名
  const savedUsername = localStorage.getItem('rememberedUsername')
  if (savedUsername) {
    loginForm.username = savedUsername
    rememberMe.value = true
  }
})
</script>

<template>
  <div class="login-container">
    <!-- 背景装饰 -->
    <div class="background">
      <div class="gradient-bg"></div>
      <div class="noise"></div>
      <div class="particles">
        <div 
          v-for="(particle, index) in particles" 
          :key="index"
          class="particle"
          :style="{
            left: `${particle.x}px`,
            top: `${particle.y}px`,
            width: `${particle.size}px`,
            height: `${particle.size}px`,
            background: particle.color,
            opacity: Math.random() * 0.5 + 0.3
          }"
        ></div>
      </div>
    </div>
    
    <!-- 导航 -->
    <nav class="nav">
      <div class="logo" @click="goToHome">
        <img src="../assets/buding-logo.svg" alt="布丁AI" />
        <span>布丁AI</span>
      </div>
    </nav>
    
    <!-- 主要内容 -->
    <div class="content">
      <!-- 左侧信息区 -->
      <div class="info-column">
        <h1 class="welcome-title">欢迎使用<br /><span class="text-gradient">布丁AI</span></h1>
        <p class="welcome-message">
          您的AI智能助手，为您提供自然对话、创作内容和解决问题的强大工具
        </p>
        <div class="features">
          <div class="feature">
            <div class="feature-icon">
              <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-message-circle"><path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"></path></svg>
            </div>
            <div class="feature-text">智能对话</div>
          </div>
          <div class="feature">
            <div class="feature-icon">
              <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-edit-3"><path d="M12 20h9"></path><path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z"></path></svg>
            </div>
            <div class="feature-text">创意写作</div>
          </div>
          <div class="feature">
            <div class="feature-icon">
              <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-code"><polyline points="16 18 22 12 16 6"></polyline><polyline points="8 6 2 12 8 18"></polyline></svg>
            </div>
            <div class="feature-text">代码助手</div>
          </div>
        </div>
      </div>
      
      <!-- 登录表单 -->
      <div class="auth-card">
        <div class="card-content">
          <h2 class="card-title">登录账户</h2>
          <p class="card-subtitle">登录您的账户，开始智能对话</p>
          
          <div class="error-container" v-if="errorMessage">
            <div class="error-message">
              <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-alert-circle"><circle cx="12" cy="12" r="10"></circle><line x1="12" y1="8" x2="12" y2="12"></line><line x1="12" y1="16" x2="12.01" y2="16"></line></svg>
              <span>{{ errorMessage }}</span>
            </div>
          </div>
          
          <form @submit.prevent="handleLogin" class="auth-form">
            <div class="form-group">
              <label for="username">用户名</label>
              <div class="input-container">
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="input-icon"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path><circle cx="12" cy="7" r="4"></circle></svg>
                <input 
                  type="text" 
                  id="username" 
                  v-model="loginForm.username" 
                  placeholder="请输入用户名"
                  @keyup.enter="!loading && handleLogin()"
                  autocomplete="username"
                />
              </div>
            </div>
            
            <div class="form-group">
              <label for="password">密码</label>
              <div class="input-container">
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="input-icon"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect><path d="M7 11V7a5 5 0 0 1 10 0v4"></path></svg>
                <input 
                  :type="showPassword ? 'text' : 'password'" 
                  id="password" 
                  v-model="loginForm.password" 
                  placeholder="请输入密码"
                  @keyup.enter="!loading && handleLogin()"
                  autocomplete="current-password"
                />
                <button 
                  type="button" 
                  class="toggle-password"
                  @click="togglePasswordVisibility"
                  tabindex="-1"
                >
                  <svg v-if="showPassword" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="eye-icon"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path><circle cx="12" cy="12" r="3"></circle></svg>
                  <svg v-else xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="eye-icon"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path><circle cx="12" cy="12" r="3"></circle><line x1="1" y1="1" x2="23" y2="23"></line></svg>
                </button>
              </div>
            </div>
            
            <div class="form-actions">
              <div class="remember-me">
                <input type="checkbox" id="remember" v-model="rememberMe" />
                <label for="remember" @click="rememberMe = !rememberMe">记住我</label>
              </div>
              <a href="#" class="forgot-password">忘记密码?</a>
            </div>
            
            <button 
              type="submit" 
              class="login-button" 
              :class="{ loading }" 
              :disabled="loading"
            >
              <span v-if="!loading">登录</span>
              <span v-else class="loader-container">
                <span class="loader"></span>
              </span>
            </button>
          </form>
          
          <div class="auth-footer">
            <span>还没有账号?</span>
            <button class="register-link" @click="goToRegister">创建账户</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
/* 全局风格 */
* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
  font-family: 'Inter', 'SF Pro Display', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
}

/* 基础变量 */
.login-container {
  /* CSS变量 */
  --primary: #6366f1;
  --primary-dark: #4f46e5;
  --primary-light: #a5b4fc;
  --surface: #ffffff;
  --surface-hover: #f9fafb;
  --background: #f3f4f6;
  --text-primary: #111827;
  --text-secondary: #4b5563;
  --text-tertiary: #9ca3af;
  --text-inverse: #ffffff;
  --border: #e5e7eb;
  --border-focus: #a5b4fc;
  --danger: #ef4444;
  --danger-light: #fee2e2;
  --radius-sm: 6px;
  --radius-md: 12px;
  --radius-lg: 20px;
  --radius-xl: 28px;
  
  position: relative;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

/* 背景样式 */
.background {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: -1;
  overflow: hidden;
  
  .gradient-bg {
    position: absolute;
    width: 100%;
    height: 100%;
    background: linear-gradient(135deg, #e0f2fe 0%, #ede9fe 50%, #fae8ff 100%);
  }
  
  .noise {
    position: absolute;
    width: 100%;
    height: 100%;
    background-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 200 200' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='noiseFilter'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.65' numOctaves='3' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23noiseFilter)' opacity='0.05'/%3E%3C/svg%3E");
    opacity: 0.3;
  }
  
  .particles {
    position: absolute;
    width: 100%;
    height: 100%;
  }
  
  .particle {
    position: absolute;
    border-radius: 50%;
    filter: blur(4px);
  }
}

/* 导航栏 */
.nav {
  padding: 24px 40px;
  display: flex;
  align-items: center;
  position: relative;
  z-index: 10;
  
  .logo {
    display: flex;
    align-items: center;
    cursor: pointer;
    gap: 10px;
    
    img {
      height: 32px;
      transition: transform 0.3s ease;
    }
    
    span {
      font-size: 20px;
      font-weight: 600;
      color: var(--text-primary);
      background: linear-gradient(90deg, #6366f1, #8b5cf6);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
    }
    
    &:hover img {
      transform: scale(1.05);
    }
  }
}

/* 主内容区 */
.content {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 0 40px 40px;
  gap: 60px;
  
  @media (max-width: 1024px) {
    flex-direction: column;
    gap: 40px;
    padding-top: 20px;
  }
}

/* 左侧信息区 */
.info-column {
  max-width: 500px;
  padding: 40px 0;
  
  .welcome-title {
    font-size: 48px;
    font-weight: 700;
    line-height: 1.1;
    color: var(--text-primary);
    margin-bottom: 24px;
    
    .text-gradient {
      background: linear-gradient(90deg, #6366f1, #8b5cf6, #d946ef);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
    }
  }
  
  .welcome-message {
    font-size: 18px;
    line-height: 1.6;
    color: var(--text-secondary);
    margin-bottom: 40px;
  }
  
  .features {
    display: flex;
    gap: 20px;
    
    .feature {
      display: flex;
      align-items: center;
      gap: 8px;
      
      .feature-icon {
        width: 42px;
        height: 42px;
        border-radius: 12px;
        background: rgba(99, 102, 241, 0.1);
        display: flex;
        align-items: center;
        justify-content: center;
        color: #6366f1;
        
        svg {
          width: 20px;
          height: 20px;
        }
      }
      
      .feature-text {
        font-size: 15px;
        font-weight: 500;
        color: var(--text-secondary);
      }
    }
  }
  
  @media (max-width: 1024px) {
    text-align: center;
    padding: 0;
    
    .welcome-title {
      font-size: 36px;
    }
    
    .welcome-message {
      font-size: 16px;
      margin-bottom: 30px;
    }
    
    .features {
      justify-content: center;
    }
  }
  
  @media (max-width: 640px) {
    .features {
      flex-direction: column;
      gap: 16px;
      
      .feature {
        justify-content: center;
      }
    }
  }
}

/* 登录卡片 */
.auth-card {
  width: 460px;
  border-radius: var(--radius-xl);
  background: rgba(255, 255, 255, 0.7);
  backdrop-filter: blur(20px);
  box-shadow: 
    0 10px 25px -3px rgba(0, 0, 0, 0.05),
    0 4px 6px -2px rgba(0, 0, 0, 0.025),
    0 0 0 1px rgba(255, 255, 255, 0.1) inset;
  overflow: hidden;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  
  &:hover {
    transform: translateY(-5px);
    box-shadow: 
      0 20px 25px -5px rgba(0, 0, 0, 0.1),
      0 10px 10px -5px rgba(0, 0, 0, 0.04),
      0 0 0 1px rgba(255, 255, 255, 0.2) inset;
  }
  
  .card-content {
    padding: 40px;
  }
  
  .card-title {
    font-size: 24px;
    font-weight: 700;
    color: var(--text-primary);
    margin-bottom: 8px;
  }
  
  .card-subtitle {
    font-size: 15px;
    color: var(--text-secondary);
    margin-bottom: 32px;
  }
  
  @media (max-width: 640px) {
    width: 100%;
    
    .card-content {
      padding: 30px;
    }
  }
}

/* 错误消息 */
.error-container {
  margin-bottom: 24px;
}

.error-message {
  background-color: var(--danger-light);
  color: var(--danger);
  padding: 12px 16px;
  border-radius: var(--radius-md);
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 8px;
  
  svg {
    width: 16px;
    height: 16px;
    flex-shrink: 0;
  }
}

/* 表单样式 */
.auth-form {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
  
  label {
    font-size: 14px;
    font-weight: 500;
    color: var(--text-secondary);
  }
}

.input-container {
  position: relative;
  display: flex;
  align-items: center;
  
  .input-icon {
    position: absolute;
    left: 14px;
    width: 18px;
    height: 18px;
    color: var(--text-tertiary);
  }
  
  input {
    width: 100%;
    height: 50px;
    background-color: var(--surface);
    border: 1px solid var(--border);
    border-radius: var(--radius-md);
    padding: 0 14px 0 44px;
    font-size: 15px;
    color: var(--text-primary);
    transition: all 0.2s ease;
    
    &::placeholder {
      color: var(--text-tertiary);
    }
    
    &:focus {
      outline: none;
      border-color: var(--border-focus);
      box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1);
    }
  }
  
  .toggle-password {
    position: absolute;
    right: 14px;
    background: none;
    border: none;
    color: var(--text-tertiary);
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0;
    
    &:focus {
      outline: none;
    }
    
    .eye-icon {
      width: 18px;
      height: 18px;
    }
  }
}

.form-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  .remember-me {
    display: flex;
    align-items: center;
    gap: 8px;
    
    input[type="checkbox"] {
      -webkit-appearance: none;
      -moz-appearance: none;
      appearance: none;
      width: 18px;
      height: 18px;
      background-color: white;
      border: 1px solid var(--border);
      border-radius: 4px;
      cursor: pointer;
      position: relative;
      transition: all 0.2s ease;
      
      &:checked {
        background-color: var(--primary);
        border-color: var(--primary);
        
        &::after {
          content: '';
          position: absolute;
          width: 5px;
          height: 10px;
          border: solid white;
          border-width: 0 2px 2px 0;
          transform: rotate(45deg);
          top: 2px;
          left: 6px;
        }
      }
      
      &:hover {
        border-color: var(--primary-light);
      }
      
      &:focus {
        outline: none;
        box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1);
      }
    }
    
    label {
      font-size: 14px;
      color: var(--text-secondary);
      cursor: pointer;
      user-select: none;
    }
  }
  
  .forgot-password {
    font-size: 14px;
    color: var(--primary);
    text-decoration: none;
    
    &:hover {
      text-decoration: underline;
    }
  }
}

.login-button {
  height: 50px;
  background: linear-gradient(135deg, #6366f1, #4f46e5);
  border: none;
  border-radius: var(--radius-md);
  color: var(--text-inverse);
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
  position: relative;
  overflow: hidden;
  
  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: -100%;
    width: 100%;
    height: 100%;
    background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
    transition: all 0.5s ease;
  }
  
  &:hover:not(:disabled) {
    box-shadow: 0 4px 12px rgba(79, 70, 229, 0.3);
    transform: translateY(-2px);
    
    &::before {
      left: 100%;
    }
  }
  
  &:active:not(:disabled) {
    transform: translateY(0);
    box-shadow: 0 2px 8px rgba(79, 70, 229, 0.3);
  }
  
  &:disabled {
    opacity: 0.7;
    cursor: not-allowed;
  }
  
  &.loading {
    background: linear-gradient(135deg, #818cf8, #6366f1);
    cursor: wait;
  }
  
  .loader-container {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
  }
  
  .loader {
    width: 24px;
    height: 24px;
    border: 3px solid rgba(255, 255, 255, 0.3);
    border-radius: 50%;
    border-top-color: white;
    animation: spin 0.8s linear infinite;
  }
  
  @keyframes spin {
    to { transform: rotate(360deg); }
  }
}

.auth-footer {
  margin-top: 32px;
  text-align: center;
  font-size: 14px;
  color: var(--text-secondary);
  
  .register-link {
    background: none;
    border: none;
    color: var(--primary);
    font-size: 14px;
    font-weight: 500;
    cursor: pointer;
    margin-left: 4px;
    transition: all 0.2s ease;
    
    &:hover {
      text-decoration: underline;
    }
  }
}
</style> 